﻿using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;

namespace MetadataDesignerLibrary
{
    public class DeclarativeSecurityAttributeRule : ILRule<DeclarativeSecurityAttributeHandle>
    {
        [ILInfo]
        public EntityHandle Parent { get; }

        [ILInfo(true)]
        public DeclarativeSecurityAction Action { get; }

        [ILInfo]
        public byte[] PermissionSet { get; }

        public DeclarativeSecurityAttributeRule(
            EntityHandle parent,
            DeclarativeSecurityAction action,
            byte[] permissionSet)
            : base()
        {
            Parent = parent;
            Action = action;
            PermissionSet = permissionSet;
        }

        public DeclarativeSecurityAttributeRule(MetadataReader reader, DeclarativeSecurityAttributeHandle declarativeSecurityAttributeHandle)
            : base(reader)
        {
            DeclarativeSecurityAttribute declarativeSecurityAttribute = reader.GetDeclarativeSecurityAttribute(declarativeSecurityAttributeHandle);
            Parent = declarativeSecurityAttribute.Parent;
            Action = declarativeSecurityAttribute.Action;
            PermissionSet = reader.GetBlobBytes(declarativeSecurityAttribute.PermissionSet);
        }

        public override DeclarativeSecurityAttributeHandle Write(MetadataDesigner designer)
        {
            MetadataBuilder builder = designer.Builder;
            return builder.AddDeclarativeSecurityAttribute(
                parent: Parent,
                action: Action,
                permissionSet: PermissionSet == null ? default : builder.GetOrAddBlob(PermissionSet));
        }
    }
}